package com.example.deepschool.service.CourseContent;

import com.example.deepschool.Model.Order;
import com.example.deepschool.Model.Response.ResponseData;
import com.example.deepschool.Model.User;
import com.example.deepschool.enums.GlobalVariables_String;
import com.example.deepschool.exception.CustomException;
import com.example.deepschool.repositories.CourseContentRepository;
import com.example.deepschool.repositories.OrderRepository;
import com.example.deepschool.repositories.UserCourseRepository;
import com.example.deepschool.util.IO;
import com.example.deepschool.util.PermissionsControl;
import com.example.deepschool.util.Redis;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Service
public class CourseContentImpl implements CourseContent {
	
	private final UserCourseRepository userCourseRepository;
	private final OrderRepository orderRepository;
	
	private final CourseContentRepository courseContentRepository;
	
	public CourseContentImpl (UserCourseRepository userCourseRepository,
	                          OrderRepository orderRepository,
	                          CourseContentRepository courseContentRepository) {
		this.userCourseRepository = userCourseRepository;
		this.orderRepository = orderRepository;
		this.courseContentRepository = courseContentRepository;
	}
	
	private void VerifyCourseMaster (Long courseID, String UUID) {
		User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
		if (! PermissionsControl.VERIFY_MODIFY_OWN_COURSE(user.getPermissions())) {
			throw new RuntimeException("权限不足");
		}
		Long[] userIds = this.userCourseRepository.selectUserIds(courseID);
		boolean isCourseMaster = false;
		for (Long userId : userIds) {
			if (userId.equals(user.getId())) {
				isCourseMaster = true;
				break;
			}
		}
		if (! isCourseMaster) {
			throw new RuntimeException("你不属于该课程的管理者");
		}
	}
	
	private void isOwnedCourse (Long courseId, String UUID) {
		User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
		Long[] userIds = this.userCourseRepository.selectUserIds(courseId);
		boolean isCourseMaster = false;
		for (Long userId : userIds) {
			if (userId.equals(user.getId())) {
				isCourseMaster = true;
				break;
			}
		}
		Order order = new Order();
		order.setUserId(user.getId());
		order.setCourseId(courseId);
		if (this.orderRepository.selectByUserIdAndCourseId(order) == null && ! isCourseMaster) {
			throw new RuntimeException("请先购买课程");
		}
	}
	
	@SneakyThrows
	@Override
	public void addCourseContent (com.example.deepschool.Model.CourseContent courseContent, String JsonContent, String UUID) {
		try {
			VerifyCourseMaster(courseContent.getCourseId(), UUID);
			String TempName = LocalDateTime.now().toString();
			String address = IO.writeJson(JsonContent, GlobalVariables_String.File_Path_CourseContent.getValue() + TempName);
			courseContent.setAddress(address);
			courseContent.setModifyTime(Timestamp.valueOf(LocalDateTime.now()));
			this.courseContentRepository.insert(courseContent);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public void update (com.example.deepschool.Model.CourseContent courseContent, String JsonData, String UUID) {
		try {
			VerifyCourseMaster(courseContent.getCourseId(), UUID);
			String TempName = LocalDateTime.now().toString();
			String address = IO.writeJson(JsonData, GlobalVariables_String.File_Path_CourseContent.getValue() + TempName);
			courseContent.setAddress(address);
			courseContent.setModifyTime(Timestamp.valueOf(LocalDateTime.now()));
			this.courseContentRepository.update(courseContent);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public void delete (com.example.deepschool.Model.CourseContent courseContent, String UUID) {
		try {
			VerifyCourseMaster(courseContent.getCourseId(), UUID);
			this.courseContentRepository.delete(courseContent.getCourseId());
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
	
	@SneakyThrows
	@Override
	public com.example.deepschool.Model.CourseContent[] getCourseContentByCourseId (Long courseId, String UUID) {
		try {
			isOwnedCourse(courseId, UUID);
			return this.courseContentRepository.select(courseId);
		} catch (Exception e) {
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}

	@SneakyThrows
	@Override
	public ResponseData getCourseContentJsonData (Long courseId, String address, String UUID) {
		try{
			isOwnedCourse(courseId,UUID);
			address=GlobalVariables_String.File_Path_CourseContent+address;
			return IO.onlineReadFile(address, 0, null);
		} catch (Exception e){
			if (e.getCause() != null) {
				String Cause = e.getCause().toString();
				if (Cause.startsWith("java.sql.SQL")) {
					throw new CustomException(500, "服务器异常.请联系管理员.");
				}
			}
			throw new CustomException(400, e.getMessage());
		}
	}
}
